package com.fhsk.file.manager.handler;

import com.alibaba.fastjson.JSONException;
import com.fhsk.file.common.exception.UnifiedException;
import com.fhsk.file.common.vo.AjaxResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.ShiroException;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.multipart.MaxUploadSizeExceededException;

import javax.validation.ConstraintViolationException;
import java.sql.SQLSyntaxErrorException;
import java.util.List;

/**
 * 统一异常处理
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    /**
     * hibernate Validated
     * post body json传参（单个参数或者对象）
     * 处理请求单个参数或者对象不满足校验规则的异常信息
     *
     * @param exception
     * @return
     * @throws Exception
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public AjaxResult exception(MethodArgumentNotValidException exception) {
        log.error(exception.getMessage(),exception);
        BindingResult result = exception.getBindingResult();
        final List<FieldError> fieldErrors = result.getFieldErrors();
        StringBuilder builder = new StringBuilder();
        for (FieldError error : fieldErrors) {
            builder.append(error.getDefaultMessage());
        }
        return AjaxResult.fail(401, builder.toString());
    }

    /**
     * javax.validation.Valid
     * get/post url传参（单个参数或者对象）
     * 处理请求单个参数或者对象不满足校验规则的异常信息
     *
     * @param exception
     * @return
     * @throws Exception
     */
    @ExceptionHandler(value = ConstraintViolationException.class)
    public AjaxResult constraintViolationExceptionHandler(ConstraintViolationException exception) {
        String message = exception.getMessage();
        String[] s = message.split(": ");
        log.error(exception.getMessage(),exception);
        return AjaxResult.fail(401, s[1]);
    }

    /**
     * 业务层统一异常处理
     *
     * @param exception
     * @return
     */
    @ExceptionHandler(value = UnifiedException.class)
    public AjaxResult unifiedExceptionHandler(UnifiedException exception) {
        if (exception.getCode() != null) {
            log.error(exception.getMessage(),exception);
            return AjaxResult.fail(exception.getCode(), exception.getMessage());
        } else {
            log.error(exception.getMessage(),exception);
            return AjaxResult.fail(exception.getMessage());
        }


    }

    /**
     * shiro权限异常
     *
     * @param exception
     * @return
     */
    @ExceptionHandler(value = ShiroException.class)
    public AjaxResult authenticationExceptionHandler(ShiroException exception) {
        log.error(exception.getMessage(),exception);
        return AjaxResult.fail("用户名密码错误");

    }

    @ExceptionHandler(value = MaxUploadSizeExceededException.class)
    public AjaxResult fileSizeLimitExceededExceptionHandler(MaxUploadSizeExceededException exception) {
        log.error(exception.getMessage(),exception);
        return AjaxResult.fail("文件过大！请小于10MB");

    }

    @ExceptionHandler(value = HttpMessageNotReadableException.class)
    public AjaxResult httpMessageNotReadableExceptionHandler(HttpMessageNotReadableException exception) {
        String errorMessage = exception.getMessage();
        String s = StringUtils.substringAfterLast(errorMessage, ":");
        String trim = StringUtils.substringBetween(s, "\"");
        log.error(exception.getMessage(),exception);
        return AjaxResult.fail("此项填写: \""+trim +"\" 格式错误");
    }

    @ExceptionHandler(value = JSONException.class)
    public AjaxResult JSONExceptionHandler(JSONException exception) {
        log.error(exception.getMessage(),exception);
        return AjaxResult.fail("填写格式错误");
    }

    @ExceptionHandler(value = NumberFormatException.class)
    public AjaxResult numberFormatExceptionHandler(NumberFormatException exception) {
        log.error(exception.getMessage(),exception);
 //       exception.printStackTrace();
        return AjaxResult.fail("填写格式错误");
    }

    @ExceptionHandler(value = SQLSyntaxErrorException.class)
    public AjaxResult sQLSyntaxErrorExceptionHandler(SQLSyntaxErrorException exception) {
        log.error(exception.getMessage(),exception);
        return AjaxResult.fail("数据库运行错误");
    }


    /**
     * 处理未定义的其他异常信息
     *
     * @param exception
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    public AjaxResult exceptionHandler(Exception exception) {
        log.error(exception.getMessage(),exception);
        return AjaxResult.fail(500, "系统错误,请联系管理员!");
    }

}

